package com.bjpowernode.config.handler;

import cn.hutool.json.JSONUtil;
import com.bjpowernode.constant.Constants;
import com.bjpowernode.entity.TUser;
import com.bjpowernode.manager.JwtManager;
import com.bjpowernode.manager.RedisManager;
import com.bjpowernode.result.R;
import com.bjpowernode.util.ResponseUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录成功的Handler
 *
 */
@Component
public class DlykAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Resource
    private JwtManager jwtManager;

    @Resource
    private RedisManager redisManager;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");

        //登录成功后，通过Authentication对象可以拿到登录的用户信息
        TUser tUser = (TUser) authentication.getPrincipal();
        String tUserJSON = JSONUtil.toJsonStr(tUser);

        //生成jwt (token)
        String token = jwtManager.generateToken(tUserJSON);

        //jwt写入redis (默认过期时间是30分钟)
        redisManager.setValue(Constants.REDIS_LOGIN_TOKEN + tUser.getId(), token, 30, TimeUnit.MINUTES);

        //获取前端是否勾选了“记住我”，拿到rememberMe这个参数的值
        Boolean rememberMe = Boolean.parseBoolean(request.getParameter("rememberMe"));
        if (rememberMe) {
            redisManager.setValue(Constants.REDIS_LOGIN_TOKEN + tUser.getId(), token, 7, TimeUnit.DAYS);
        }

        //登录成功后，返回一个“统一的结果对象”
        R result = R.OK(token);

        //把“统一的结果对象”R写出到前端
        ResponseUtil.write(response, result);
    }
}
